<template>
	<div>
		<!-- 面包屑 -->
		<el-breadcrumb separator-class="el-icon-arrow-right">
			<el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
			<el-breadcrumb-item>角色管理</el-breadcrumb-item>
			<el-breadcrumb-item>角色列表</el-breadcrumb-item>
		</el-breadcrumb>
		<el-card>
			<el-row>
				<el-col><el-button type="primary" @click="showAddRoleDialog">添加角色</el-button></el-col>
			</el-row>
			<el-table :data="roleList" border stripe>
				<el-table-column type="expand">
					<template slot-scope="scope">
						<el-row :class="['bdbottom', a == 0 ? 'bdtop' : '', 'vcenter']" v-for="(itema, a) in scope.row.children" :key="itema.id">
							<!-- 一级权限 -->
							<el-col :span="5">
								<el-tag closable @close="deleteThirdPer(scope.row, itema.id)">{{ itema.authName }}</el-tag>
								<i class="el-icon-caret-right"></i>
							</el-col>
							<!-- 其他的权限 -->
							<el-col :span="19">
								<el-row :class="[b == 0 ? '' : 'bdtop', 'vcenter']" v-for="(itemb, b) in itema.children" :key="itemb.id">
									<el-col :span="6">
										<el-tag type="success" closable @close="deleteThirdPer(scope.row, itemb.id)">{{ itemb.authName }}</el-tag>
										<i class="el-icon-caret-right"></i>
									</el-col>
									<el-col :span="18">
										<el-tag type="warning" v-for="(itemc, c) in itemb.children" :key="itemc.id" closable @close="deleteThirdPer(scope.row, itemc.id)">
											{{ itemc.authName }}
										</el-tag>
									</el-col>
								</el-row>
							</el-col>
						</el-row>
					</template>
				</el-table-column>
				<el-table-column type="index"></el-table-column>
				<el-table-column label="角色名称" prop="roleName"></el-table-column>
				<el-table-column label="角色描述" prop="roleDesc"></el-table-column>
				<el-table-column label="操作" width="300px">
					<template slot-scope="scope">
						<el-button type="primary" icon="el-icon-edit" size="mini">编辑</el-button>
						<el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteRole(scope.row)">删除</el-button>
						<el-button type="warning" icon="el-icon-setting" size="mini" @click="showSetRightsDialog(scope.row)">分配权限</el-button>
					</template>
				</el-table-column>
			</el-table>
		</el-card>
		<el-dialog title="分配权限" :visible.sync="setRightsdialog" width="50%" @close="clearPerId">
			<span>
				<el-tree ref="rightsRef" :data="rightsList" :props="defaultProps" show-checkbox node-key="id" default-expand-all :default-checked-keys="checkedArray"></el-tree>
			</span>
			<span slot="footer" class="dialog-footer">
				<el-button @click="setRightsdialog = false">取 消</el-button>
				<el-button type="primary" @click="addRights">确 定</el-button>
			</span>
		</el-dialog>
		<el-dialog title="添加角色" :visible.sync="addRoleDialog" @close="addRoleDialogClosed">
			<el-form ref="addRoleRef" :model="addRoleForm" :rules="addRoleRules" label-width="100px">
				<el-form-item label="角色名称" prop="roleName"><el-input v-model="addRoleForm.roleName" autocomplete="off"></el-input></el-form-item>
				<el-form-item label="角色描述"><el-input type="textarea" :rows="2" placeholder="请输入内容" v-model="addRoleForm.roleDesc"></el-input></el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="addRoleDialog = false">取 消</el-button>
				<el-button type="primary" @click="addRoleDo">确 定</el-button>
			</div>
		</el-dialog>
	</div>
</template>
<script>
export default {
	data() {
		return {
			roleList: [],
			setRightsdialog: false,
			rightsList: [],
			defaultProps: {
				children: 'children',
				label: 'authName'
			},
			checkedArray: [],
			roleId: '',
			addRoleDialog: false,
			addRoleForm: {
				roleName: '',
				roleDesc: ''
			},
			addRoleRules: {
				roleName: [{ required: true, message: '请输入角色名字', trigger: 'blur' }]
			}
		};
	},
	methods: {
		async getRolesList() {
			const { data: res } = await this.$http.get('roles');

			if (res.meta.status != 200) {
				return this.$message.error('获取角色失败');
			}
			this.roleList = res.data;
		},
		deleteThirdPer(role, pid) {
			this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			})
				.then(async () => {
					const { data: res } = await this.$http.delete('roles/' + role.id + '/rights/' + pid);
					if (res.meta.status !== 200) {
						return this.$message.error('删除权限失败');
					}
					this.$message.success('删除权限成功');
					role.children = res.data;
				})
				.catch(() => {
					this.$message({
						type: 'info',
						message: '已取消删除'
					});
				});
		},
		async showSetRightsDialog(role) {
			//在之后的树形控件 拿不到role的id 所以在这里先保存到data中
			this.roleId = role.id;
			const { data: res } = await this.$http.get('rights/tree');
			if (res.meta.status != 200) {
				return this.$message.error('获取权限数据失败');
			}
			this.rightsList = res.data;
			this.getLeafKeys(role, this.checkedArray);
			this.setRightsdialog = true;
		},
		// 递归获取被选中的权限id
		getLeafKeys(node, arr) {
			if (!node.children) {
				return arr.push(node.id);
			}
			node.children.forEach(item => {
				this.getLeafKeys(item, arr);
			});
		},
		// 清空权限id
		clearPerId() {
			this.checkedArray = [];
		},
		async addRights() {
			const keys = [...this.$refs.rightsRef.getCheckedKeys(), ...this.$refs.rightsRef.getHalfCheckedKeys()];
			const Ids = keys.join(',');
			const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, {
				rids: Ids
			});
			if (res.meta.status != 200) {
				return this.$message.error('分配权限失败');
			}
			this.$message.success('分配权限成功');
			this.getRolesList();
			this.setRightsdialog = false;
		},
		deleteRole(role) {
			this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			})
				.then(async () => {
					const { data: res } = await this.$http.delete('roles/' + role.id);
					if (res.meta.status !== 200) {
						return this.$message.error('删除角色失败');
					}
					this.$message.success('删除角色成功');
					this.getRolesList();
				})
				.catch(() => {
					this.$message({
						type: 'info',
						message: '已取消删除'
					});
				});
		},
		showAddRoleDialog() {
			this.addRoleDialog = true;
			this.addRoleForm = {};
		},
		addRoleDialogClosed() {
			console.log(this.$refs.addRoleRef);
			this.$refs.addRoleRef.resetFields();
		},
		addRoleDo() {
			this.$refs.addRoleRef.validate(async valid => {
				if (!valid) return;
				const { data: res } = await this.$http.post('roles', { roleName: this.addRoleForm.roleName, roleDesc: this.addRoleForm.roleDesc });
				if (res.meta.status != 201) {
					this.$message.error('添加角色失败');
				}
				this.$message.success('添加角色成功');
				this.addRoleDialog = false;
				this.getRolesList();
			});
		}
	},
	created() {
		this.getRolesList();
	}
};
</script>
<style scoped>
.el-tag {
	margin: 10px;
}

.bdtop {
	border-top: 1px solid #eee;
}

.bdbottom {
	border-bottom: 1px solid #eee;
}

.vcenter {
	display: flex;
	align-items: center;
}
</style>
